import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.PrivateKey;
import java.security.PublicKey;

public class KeyAgree5_6 {
    public static SecretKeySpec createKey(PublicKey pbk,PrivateKey prk) throws Exception{
        String mode = "AES";
        //通过命令行参数传入公钥和私钥文件名，第一个命令行参数为对方的公钥文件名，第二个命令行参数为自己的私钥文件名。
        /*FileInputStream f1 = new FileInputStream(inpub);
        ObjectInputStream b1 = new ObjectInputStream(f1);
        PublicKey pbk = (PublicKey)b1.readObject();
        FileInputStream f2 = new FileInputStream(inpri);
        ObjectInputStream b2 = new ObjectInputStream(f2);
        PrivateKey prk = (PrivateKey) b2.readObject();*/
        KeyAgreement ka = KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);

        byte[] s=ka.generateSecret();
        byte [] sb = new byte[24];
        for(int i=0;i<24;i++){
            sb[i]=s[i];
        }
        System.out.println("共享信息为：");
        for(int i=0;i<sb.length;i++){
            System.out.print(sb[i]+" ");
        }
        System.out.println();
        SecretKeySpec k=new  SecretKeySpec(sb,mode);

        return k;
    }
}

